package com.springboot.config;


import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;

@Configuration
@ComponentScan(basePackages="com.springboot")
@SpringBootApplication
@PropertySource(value="classpath:jdbc.properties")
public class SpringBootConfig extends WebMvcConfigurerAdapter{
	
	@Value("${jdbc.driverClassName}")
	private String jdbcDriverClassName;
	
	@Value("${jdbc.url}")
	private String jdbcUrl;
	
	@Value("${jdbc.username}")
	private String jdbcUserName;
	
	@Value("${jdbc.password}")
	private String jdbcPassword;
	
	

	public static void main(String[] args) {
		SpringApplication.run(SpringBootConfig.class, args);
	}

	@Bean
	public FastJsonHttpMessageConverter fastJson() {
		FastJsonHttpMessageConverter fastJson = new FastJsonHttpMessageConverter();
		return fastJson;
	}
	
	
	/*********************************SpringMVC整合Mybatis**************************************/
	
	/**
	 * 数据源连接池
	 * @return
	 */
	@Bean(initMethod="init",destroyMethod="close")
	public DataSource druidDataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName(jdbcDriverClassName);
		dataSource.setUrl(jdbcUrl);
		dataSource.setUsername(jdbcUserName);
		dataSource.setPassword(jdbcPassword);
		dataSource.setInitialSize(10);//初始化创建连接数量
		dataSource.setMaxActive(50);//最大并发量
		dataSource.setMaxIdle(5);//最大空闲数量
		dataSource.setMinIdle(2);
		dataSource.setMaxWait(60000);
		return dataSource;
	}
	
	/**
	 * SqlSessionFactory
	 * @return
	 */
	@Bean
	public SqlSessionFactoryBean sqlSessionFactory() {
		SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
		sqlSessionFactory.setDataSource(this.druidDataSource());
		return sqlSessionFactory;
	}
	
	
	
}
